from time import sleep
import logging


class log(object):
    logDebug = True
    def __init__(self, logMsg = None):
        if logMsg:
            # pass
            print(logMsg)

    def debug(logMsg):
        if  logMsg is None or logMsg == '':
            print('日志传入的参数为空')
            return False
        # pass
        print(logMsg)


        # 向文件中追加一个字符串
    def file_put_content(file: str, msg: str):
        """
        向文件中追加一个字符串
        :param file: 文件名称
        :param msg: 要添加的文本
        :return: bool 是否添加成功
        """
        # 文件句柄
        f = None

        # 打开失败时的延迟时间(毫秒)
        times = 1

        # 无限尝试
        while True:
            try:
                f = open(file, mode='w+', encoding='utf-8')
            except OSError:
                # 打开失败,延迟 毫秒
                sleep(1)
                # 下次翻倍延迟
                times *= 2

            # 如果文件被打开或次数太多,则跳出
            if times > 1024:
                return False

            # 文件被成功打开
            if f is not None:
                break

        # 写入文件
        f.write(msg)
        f.close()
        return True




    def save(logMsg):
        # 创建一个logger
        logger = logging.getLogger('mylogger')
        logger.setLevel(logging.DEBUG)
        # 创建一个handler，用于写入日志文件
        fh = logging.FileHandler('test.log')
        fh.setLevel(logging.DEBUG)
        # 再创建一个handler，用于输出到控制台
        ch = logging.StreamHandler()
        ch.setLevel(logging.DEBUG)
        # 定义handler的输出格式
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        fh.setFormatter(formatter)
        ch.setFormatter(formatter)
        # 给logger添加handler
        logger.addHandler(fh)
        logger.addHandler(ch)
        logger.info(str(logMsg))
